﻿var from = (function () {
    function cinit(f)
    {
        f.initing = true;
        try {
            f.id = webjs.newid();
            f.name = "from_" + f.id;
            f.tabname = f.name + "_tabname";
            if (f.applyTo != "") {
                $("#" + f.applyTo).attr("id", f.id);
                $("#" + f.id).append("<div id='" + f.tabname + "'>");
                $("#" + f.tabname).tabs({
                    fit: true
                });
                setgrid(f);
                var model = f.datasource.modeldata.childmodel[f.editindex];
                model.length = f.datasource.modeldata.childmodel.length;
                setchildfrom(f, model, model.childitem);
            }
        }
        finally
        {
            f.initing = false;
        }
    }
    function setgrid(f) {
        for (var i in f.datasource.modeldata.childmodel) {
            if (i >= f.showdiv) break;
            var model = f.datasource.modeldata.childmodel[i];;
            if (!model.visible) continue;
            var grid = new datagrid();
            grid.datasource = f.datasource.getcmsource(i);
            grid.datasource.page = 1;
            grid.applyTo = f.id + "tt" + i;
            $("#" + f.tabname).tabs("add", {
                title: model.title,
                content: '<div id="' + f.id + 'tt' + i + '"/>',
                selected: false
            })
           
            $("#" + grid.applyTo).panel({ fit: true });
            grid.fit = true;
            f.griditems[i] = grid;
            f.childmodel[i] = grid.datasource.modeldata;
            if (i == f.edid) {
                grid.isremove = true;
                grid.onRemove = function (row) {
                    $.messager.confirm('删除', '您确认删除选择数据吗？', function (ok) {
                        if (ok) {
                            var grid = f.griditems[f.edid];
                            row.StateBase = 2
                            grid.loading();
                            f.Save(row);
                        }
                    });
                }
                grid.onSubmit = function () {
                    $.messager.confirm('提交', '您确认提交选择数据吗？', function (ok) {
                        if (ok) {
                            var grid = f.griditems[f.edid];
                            grid.loading();
                            f.onSubmit();
                        }
                    });
                }
            }
           
            if (i == f.suid) {
                grid.issearch = true;
                grid.onSearch = function (w) {
                    if (w == 0) {
                        findindex1(f);
                    }
                    if (w == 1) {
                        f.loadforeign(f.suid, [], function (e) {
                            var grid = f.griditems[f.suid];
                            grid.load(e);
                        });
                    }
                }
            }
           grid.onDblClickRow = function (grid, rowIndex, rowData) {
                f.editItem = rowData;
                $("#" + f.tabname).tabs("select", f.showdiv);
                f.editgrid = grid;
                f.onSetValue();
            }
            grid.parent = f;
            grid.tabindex = i;
            grid.init();
        }
        $("#" + f.tabname).tabs({
            onSelect: function (title, index) {
                if (f.setval) return;
                if (f.initing) return;
                if (f.onTabSelect)
                {
                    var t = f.onTabSelect(title, index);
                    if (t === false)
                        return;
                }
                f.tabindex = index;
                if (title == '序列码')
                {
                    findsn(f);
                    if (f.sninput)
                        $(f.sninput).focus();
                    return;
                }
                if (f.parent.isonline) {
                    var grid = f.griditems[index];
                    if (grid) {
                        var item = f.childdata[index];
                        if (item) {
                            grid.loading();
                            grid.load(item);
                        }
                        else {
                            if (index == 0) {
                                findindex1(f);
                            }
                            else {
                                findindex2(f);
                            }
                        }
                    }
                }
            }
        });
    }
    function searchfind(f) {
        findindex1(f, function (f) {
            findindex2(f);
        });
    }
    function findindex1(f,fn)
    {
        var grid = f.griditems[0];
        grid.load(null);
        //var w1 = { ColumnName: "STAYNUM", Value: "0", Symbol: ">" };
        var wobj = f.parent.childWhere;
        //wobj.push(w1);
        f.loadforeign(0, wobj, function (e) {
            var grid = f.griditems[0];
            grid.load(e);
            if (fn)
                fn(f);
        });
    }
    function findindex2(f,fn)
    {
        var grid = f.griditems[1];
        if (grid) {
            grid.load(null);
            var w = null;
            f.loadforeign(1, w, function (e) {
                var grid = f.griditems[1];
                grid.load(e);
            })
        }
    }
    function findsn(f)
    {
        if (f.editItem.SEQUENCECODE)
        {   
            var ae = 0;
            for (var i in f.griditems) {
                if (f.editgrid.name == f.griditems[i].name) {
                    ae = i;
                    break;
                }
            }
            if (ae > 0) {
                var grid = f.griditems[1];
                if (grid) {
                    grid.datasource.loadforeign(0, f.editItem, null, function (e) {
                        $(f.tg).datagrid('loadData', e);
                    });

                }
            }
        }
    }
    function setchildfrom(f, model, items) {
        var l = model.length;
        var name = f.id + 'tt' + l;
        f.ffnmae = name;
        $("#" + f.tabname).tabs("add", {
            title: f.cztitle,
            content: '<div id="' + name + '"/>',
        })
        $("#" + name).panel({
            fit: true
        });
        var main = name + "_main";
        var div = '<div id="' + main + '" style="padding:0 20px">';
        var tdiv = '<div class="m-item" style="border-bottom:1px solid #eee">';
        var ldiv = '<div class="m-label">$$$1<div>';
        var idiv = '<div><input type="text" class="easyui-textbox" name="$$$2" style="width:200px;height:30px;font-size: 16px;"/></div></div>'
        var but = '<div style="text-align:center;margin-top:30px">';
        var save = ' <a href="#" id="' + f.ffnmae + '_save" class="easyui-linkbutton" style="width:40%"><span style="font-size:16px">保存</span></a>';
        var clear = ' <a href="#" id="' + f.ffnmae + '_clear" class="easyui-linkbutton" style="width:40%"><span style="font-size:16px">清空</span></a>'

        var jsdiv = "</div>"
        var body = "";
        var dis = "";
        if (f.onChildFrom) {
            f.onChildFrom(f, model, items);
        }
        $("#" + name).append(div + "</div>");
        for (var i in items) {
            var mm = items[i];
            if (mm.field == "ROWINDEX" || mm.field == "CREATEDBY" || mm.field == "CREATIONDATE") continue;
            if (mm.visible) {
                dis = "";
                if (mm.disabled)
                    dis = "disabled";
                var box = new textbox();
                box.field = mm.field;
                box.title = mm.title;
                box.disabled = dis;
                if (mm.field == 'MATERIALCODE' || mm.field == 'DEPOTWBS') {
                    box.buttonText = "指导";
                }
                box.applyTo = main;
                box.parent = f;
                box.required = mm.required;
                f.boxs.push(box);
                box.init();
            }
        }
        $("#" + main).append(but + save + clear + jsdiv);

        $("#" + f.ffnmae + "_save").linkbutton({
            iconCls: 'icon-save', onClick: function () {
                f.onSave();
            }
        });
        $("#" + f.ffnmae + "_clear").linkbutton({
            iconCls: 'icon-clear', onClick: function () {
                f.clear();
            }
        });
    }
    function loading(f, txt) {
        var text = "操作中请稍等。。。";
        if (txt)
            text = txt;
        var _1c7 = $("#" + f.id).panel();
        if (!_1c7.children("div.datagrid-mask").length) {
            $("<div class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(_1c7);
            var msg = $("<div class=\"datagrid-mask-msg\" style=\"display:block;left:50%\"></div>").html(text).appendTo(_1c7);
            msg._outerHeight(40);
            msg.css({ marginLeft: (-msg.outerWidth() / 2), lineHeight: (msg.height() + "px") });
        }
    }
    function loaded(f) {
        var _1c8 = $("#" + f.id).panel();
        _1c8.children("div.datagrid-mask-msg").remove();
        _1c8.children("div.datagrid-mask").remove();
    }
    return {
        parent: null,
        datasource: null,
        applyTo: "",
        selectItem: null,
        title: "",
        griditems: [],
        childmodel: [],
        childdata: [],
        boxs:[],
        editItem: null,
        isupdate: false,
        showdiv: 2,
        cztitle: "仓库作业",
        editindex: 1,
        edittab: 0,
        edid: 1,//操作索引
        suid:0,//查询索引
        init: function () {
            cinit(this);
        },
        reinit: function () {
            $("#" + this.id).empty();
            $("#" + this.id).attr("id", this.applyTo);
            cinit(this);
        },
        close: function () {
            $("#" + this.id).dialog('close');
        },
        show: function () {
            var f = this;
           
            $("#" + this.id).dialog({
                title: this.title,
                fit: true,
                modal: true,
                resizable: false,
                draggable:false,
                onClose: function () {
                    $(this).panel('destroy');
                    if (f.onClose)
                        f.onClose();
                    f.isupdate = false;
                    window.f = null;
                }
            });
            $(".datagrid-toolbar > table").each(function () {
                $(this).css("width", "100%");
            });
            $('.datagrid-toolbar > table td:last').each(function () {
                $(this).css("text-align", "right");
            });
            window.f = this;
            $("#" + this.tabname).tabs("select", 0);
        },
        loadforeign: function (index, w, f) {
            var grid = this.griditems[index];
            grid.loading();
            this.datasource.loadforeign(index, this.datasource.selectItem, w, function (e) {
                if (e && e.error) {
                    grid.loaded();
                    $.messager.alert('异常', e.errormsg, 'error');
                    return;
                }
                f(e);
            });
        },
        findbox: function (field) {
            var box = null;
            var name = field.toUpperCase();
            for (var i in this.boxs) {
                var e = this.boxs[i];
                if (e.field == name) {
                    box = e;
                    break;
                }
            }
            return box;
        },
        onChange: function (name, newValue, oldValue) {
            if (newValue == oldValue) return;
            var f = this;
            if (f.notChange) return;
            if (f.editgrid == undefined)
                f.editgrid = f.griditems[0]
            if (this.parent.onChange) {
                var change = f.parent.onChange(f, name, newValue, oldValue);
                if (change === false)
                    return;
            }
            if (name == 'MATERIALCODE') {
                if (newValue.length <= 5) return;
                f.clear();
                var fay = this.editgrid.datasource.finditem("MATERIALCODE")
                var fn = fay.foreign.displayname;
                var data = f.childdata[0];
                var row;
                var item = null;
                if (data && data.rows) {
                    for (var i in data.rows) {
                        row = data.rows[i];
                        if (row.MATERIALCODE == newValue || row.MCODE == newValue || row.CUSTOMEAN13 == newValue || row[fn] == newValue) {
                            item = row;
                            break;
                        }
                    }
                }
                if (item == null) {
                    if (data.total > 10) {
                        var wobj = [];
                        var w1 = { StartFH: "(", ColumnName: "MCODE", Value: newValue };
                        var w2 = { Relation: "or", ColumnName: "CUSTOMEAN13", Value: newValue, EndFH: ")" };
                        wobj.push(w1);
                        wobj.push(w2);
                        f.loadforeign(0, wobj, function (e) {
                            if (e.total > 0) {
                                f.editItem = null;
                                f.onSetValue(e.rows[0]);
                            }
                            else
                                $.messager.alert('异常', "扫描的条码" + newValue + "不在本次任务范围!", 'error');
                        })
                    }
                    else {
                        $.messager.alert('异常', "扫描的条码" + newValue + "不在本次任务范围!", 'error');
                    }
                }
                else {

                    f.editItem = null;
                    f.notChange = true;
                    try {
                        f.onSetValue(item);
                    }
                    finally {
                        f.notChange = false;
                    }
                }
            }
            if (name == 'DEPOTWBS') {
                f.findbox("DEPOTWBS").value = null;
            }
            if (name == "NUM") {
                if (!$.isNumeric(newValue))
                    f.findbox("NUM").val("");
            }
        },
        clear: function () {
            for (var i in this.boxs)
                this.boxs[i].clear();
            if (this.tabname)
                $("#" + this.tabname).tabs('close', "序列码");
        },
        onTextClick: function (name) {
            var f = this;
            if (name == 'MATERIALCODE') {
                this.editgrid = this.griditems[0];
                var data = this.childdata[0];
                if (data && data.total > 0) {
                    for (var i in data.rows) {
                        var row = data.rows[i];
                        if (row.STAYNUM > 0) {
                            this.editItem = row;
                            this.onSetValue();
                            return;
                        }
                    }
                }
            }
            if (name == "DEPOTWBS") {
                getDeportwbs(f);
            }
            function dsetvalue(f, obj) {
                f.notChange = true;
                f.findbox("DEPOTWBS").val(obj.ID, obj.CODE);
                if (obj.WAREHOUSENAME) {
                    var box = f.findbox('HQNAME');
                    if (box)
                        box.val(obj.WAREHOUSENAME);
                }
                if (obj.SUBNO && f.editItem.ISPERIOD)
                    f.findbox("SUBNO").val(obj.SUBNO);
                if (obj.BATCHNO && f.editItem.BATCH)
                    f.findbox("BATCHNO").val(obj.BATCHNO);
                if (obj.KYNUM) {
                    if (obj.KYNUM < f.editItem.STAYNUM)
                        f.findbox("NUM").val(obj.KYNUM);
                    else {
                        var num = f.findbox("NUM").val();
                        if (f.editItem.STAYNUM && num < f.editItem.STAYNUM)
                            f.findbox("NUM").val(f.editItem.STAYNUM);
                    }
                }
                f.notChange = false;
            }
            function getDeportwbs(f) {
                if (f.editItem) {
                    var grid = f.griditems[1];
                    var item = grid.datasource.finditem("DEPOTWBS");
                    var fdata = item.foreign;
                    fdata.eventrow = webjs.jsonval(f.editItem);
                    var row = f.parent.datasource.selectItem;
                    var josn = "fdata=" + webjs.jsonval(fdata) + "&ActionItem=" + webjs.jsonval(row);
                    f.parent.datasource.submit("loadforeign", josn, function (e) {
                        if (e && e.error) {
                            $.messager.alert('异常', e.errormsg, 'error');
                            return;
                        }
                        if (e) {
                            if (e.total == 0) {
                                $.messager.alert('消息', "没有找到可用货位！", 'error');
                            }
                            if (e.total == 1) {
                                dsetvalue(f, e.rows[0]);
                            }
                            if (e.total > 1) {
                                var id = webjs.newid() + "_depotwbs";
                                var wbsid = id + "_grid";
                                var cms = [];
                                for (var i in e.rows[0]) {
                                    if (i == 'WAREHOUSENAME' || i == 'CODE' || i == 'SUBNO' || i == 'BATCHNO' || i == 'KYNUM' || i == 'NUM' || i == 'ZYNUM') {
                                        if (i == "WAREHOUSENAME") {
                                            var obj = { field: i, title: '货区', width: 60, align: 'center', sortable: false };
                                            cms.unshift(obj);
                                        }
                                        if (i == "CODE") {
                                            var obj = { field: i, title: '货位', width: 60, align: 'center', sortable: false };
                                            cms.unshift(obj);
                                        }
                                        if (i == 'SUBNO') {
                                            if (f.editItem.ISPERIOD) {
                                                var obj = { field: i, title: '有效期', width: 40, align: 'center', sortable: false };
                                                cms.push(obj);
                                            }
                                        }
                                        if (i == 'BATCHNO') {
                                            if (f.editItem.BATCH) {
                                                var obj = { field: i, title: '批次', width: 40, align: 'center', sortable: false };
                                                cms.push(obj);
                                            }
                                        }
                                        if (i == 'KYNUM') {
                                            var obj = { field: i, title: '可用数', width: 30, align: 'center', sortable: false };
                                            cms.push(obj);
                                        }
                                        if (i == 'NUM') {
                                            var obj = { field: i, title: '库存', width: 30, align: 'center', sortable: false };
                                            cms.push(obj);
                                        }
                                        if (i == 'ZYNUM') {
                                            var obj = { field: i, title: '占用数', width: 30, align: 'center', sortable: false };
                                            cms.push(obj);
                                        }
                                    }
                                }
                                $("body").append("<div id='" + id + "'><table id='" + wbsid + "'></table></div>");
                                $("#" + wbsid).datagrid({
                                    singleSelect: true,
                                    cache: false,
                                    fit: true,
                                    fitColumns: true,
                                    border: false,
                                    loadMsg: "数据读取中，请稍后。。。",
                                    columns: [cms],
                                    onSelect: function (rowIndex, rowData) {
                                        dsetvalue(f, rowData);
                                        $("#" + id).dialog('close');
                                    },
                                    data: e.rows
                                });
                                $("#" + id).dialog({
                                    title: "推荐货位",
                                    modal: true,
                                    width: 320,
                                    height: 300
                                });
                            }
                        }
                    });
                }
            }
        },
        onSubmit: function () {
            var f = this;
            var item = f.parent.datasource.selectItem;
            f.isupdate = true;
            this.datasource.clickcommand("submit", item, function (e) {
                var grid = f.griditems[1];
                grid.loaded();
                if (e && e.error) {
                    $.messager.alert('异常', e.errormsg, 'error');
                    return;
                }
                $.messager.alert('消息', '提交完成');
                f.clear();
            });
        },
        Save: function (obj) {
            var f = this;
            f.isupdate = true;
            var item = f.parent.datasource.selectItem;
            var model = f.childmodel[f.edid].name;
            item[model] = [obj];
            this.datasource.clickcommand("save", item, function (e) {
                f.loaded();
                if (e && e.error) {
                    $.messager.alert('异常', e.errormsg, 'error');
                    return;
                }
                searchfind(f);
                if (f.parent.onSaveed)
                    f.parent.onSaveed(f, obj);
                else
                    f.clear();
                if (f.editItem && f.editItem.SEQUENCECODE) {
                    var data = {};
                    data.rows = [];
                    data.total = 0;
                    $(f.tg).datagrid('loadData', data);
                }
                // $.messager.alert('消息', '操作完成');
            });
        },
        onSave: function () {
            try {
                var obj = {};
                var f = this;
                for (var i in f.boxs) {
                    var box = f.boxs[i];
                    var vv = box.val();
                    if (box.required) {
                        if (vv == "") {
                            $.messager.alert('异常', box.title + "不能为空！", 'error');
                            return;
                        }
                    }
                    obj[box.field] = vv;
                }
                loading(this);
                var ae = 0;
                for (var i in this.griditems) {
                    if (this.editgrid.name == this.griditems[i].name) {
                        ae = i;
                        break;
                    }
                }
                if (this.editItem && this.editItem.SEQUENCECODE) {
                    var rows = $(f.tg).datagrid('getRows');
                    if (rows.length == 0) {
                        $.messager.alert('异常', "商品为序列号管理，必须录入系列号！", 'error');
                        f.loaded();
                        return;
                    }
                    var model = f.childmodel[1].childmodel[0].name;
                    for (var i in rows) {
                        if (rows[i].ID && rows[i].ID > 0)
                            rows[i].StateBase = 3;
                    }

                    obj[model] = rows;
                    if (f.delRows) {
                        for (var i in f.delRows)
                            obj[model].push(f.delRows[i]);
                        f.delRows = [];
                    }
                }
                if (ae == 0) {
                    obj.StateBase = 0;
                    if (this.editItem)
                        obj.SOURCEROWID = this.editItem.ID;
                }
                else {
                    obj.StateBase = 3;
                    obj.GetOldObject = this.editItem;
                    for (var i in this.editItem) {
                        if (obj[i] == undefined)
                            obj[i] = this.editItem[i];
                    }
                }
                if (this.parent.onSave) {
                    var change = this.parent.onSave(this, obj);
                    if (change === false)
                        return;
                }
                this.Save(obj);
            }
            catch (e) {
                $.messager.alert('异常', e.message, 'error');
                f.loaded();
            }
        },
        onSetValue: function (item) {
            if (this.editItem == null)
                this.editItem = item;
            var f = this;
            f.setval = true;
            try {
                var data = this.editItem
                if (f.editgrid == undefined)
                    f.editgrid = f.griditems[0]
                var source = f.editgrid.datasource;
                for (var i in f.boxs) {
                    var box = f.boxs[i];
                    var item1 = source.getitem(box.field);
                    if (item1 != null && item1.foreign && item1.foreign.isfkey) {
                        var text = data[item1.foreign.displayname];
                        var val = data[box.field];
                        box.val(val, text);
                        continue;
                    }
                    if (item1 != null && item1.comvtp && item1.comvtp.isvtp)
                    {
                        var com = item1.comvtp;
                        if (data[box.field] !== "" && com) {
                            for (var i in com.items) {
                                if (com.items[i].Value == data[box.field]) {
                                    box.val(com.items[i].Value, com.items[i].Text);
                                    break;
                                }
                            }
                        }
                        continue;
                    }
                    box.val(data[box.field]);
                } 
            }
            finally
            {
                if (f.onSetValueed) {
                    f.onSetValueed(this.editItem);
                }
                f.setval = false;
            }
        },
        updateData: function (index, data) {
            var f = this;
            f.childdata[index] = data;
        },
        onChildFrom: function (f, model, items) {
            if (this.parent.onChildFrom) {
                this.parent.onChildFrom(f, model, items);
            }
        },
        setText: function (field, text) {
            var box = this.findbox(field);
            if (box)
                box.val(text);
        },
        childsearch: function () {
            searchfind(this);
        },
        loaded: function () {
            loaded(this);
        },
        loading: function (txt) {
            loading(this, txt);
        },
        selectTab: function (be)
        {
            var tabs = $("#" + f.tabname).tabs("tabs");
            var count = tabs.length - 1;
            var index = 0;
            if (this.tabindex > 0 && this.tabindex < count) {
                if (be)
                    index = (this.tabindex + 1);
                else
                    index = (this.tabindex - 1);
            }
            else {
                if (be) {
                    if (this.tabindex == 0)
                        index = 1;
                    if (this.tabindex == count)
                        index = 0;
                }
                else {
                    if (this.tabindex == 0)
                        index = count;
                    if (this.tabindex == count)
                        index = (this.tabindex - 1);
                }
            }
            $("#" + this.tabname).tabs("select", index);
        },
        keydown: function (f,key) {
            var i = f.tabindex;
            var grid = f.griditems[i];
            if (grid) {
                if (key.keyCode == "50")
                    grid.selectRow(-1);
                if (key.keyCode == "56")
                    grid.selectRow(1);
                if (key.keyCode == "53")
                    grid.onDblClickRow(grid, grid.selectindex, grid.datasource.selectItem);
                if (key.keyCode == "55")
                    grid.nfpage(-1)
                if (key.keyCode == "57")
                    grid.nfpage(1)
                if (key.keyCode == "49")
                    grid.buttonclick(0);
                if (key.keyCode == "51")
                    grid.buttonclick(1);
                if (key.keyCode == "8") {
                    $.messager.confirm('关闭', '您确认关闭编辑窗体吗？', function (ok) {
                        if (ok) {
                            $("#" + f.id).dialog("close");
                        }
                    });
                }
            }
            else {
                if (key.keyCode == "0") {
                    var name = "#" + f.ffnmae + "_main";
                    var inputs = $(name + " input[disabled!='disabled']");
                    if (f.fosindex == undefined)
                        f.fosindex = 0;
                    else
                        f.fosindex = (f.fosindex + 1);
                    if (f.fosindex > inputs.length - 1)     // 判断是否是最后一个输入框
                        f.fosindex = 0;
                    inputs[f.fosindex].focus();       //设置焦点
                    inputs[f.fosindex].select();       //选中文字
                }
            }
        }
        
    }
})